package edu.imu.question.service.impl;

import edu.imu.question.config.constans.UserStatusEnum;
import edu.imu.question.controller.form.SignupForm;
import edu.imu.question.entity.ResponseResult;
import edu.imu.question.entity.User;
import edu.imu.question.mapper.UserMapper;
import edu.imu.question.service.SignupService;
import edu.imu.question.util.EncryptUtil;
import edu.imu.question.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SignupServiceImpl implements SignupService {

    private final UserMapper userMapper;

    @Autowired
    public SignupServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public ResponseResult signup(SignupForm form) {
        final int i = userMapper.countByUsername(form.getUsername());
        if(i>0){
            return ResponseResult.error("用户名已被占用，请换一个吧！",null);
        }
        final User user = new User();
        user.setUsername(form.getUsername());
        final String password = form.getPassword();
        final String passSalt = RandomUtil.randomNumber(5);
        final String encryptPass = EncryptUtil.encryptPassword(password, passSalt);
        user.setPassword(encryptPass);
        user.setPasswordSalt(passSalt);
        user.setIsVip(0);
        user.setStatus(UserStatusEnum.NORMAL.getStatus());
        user.setCreateDate(new Date());
        userMapper.addUser(user);
        return ResponseResult.ok("注册成功！",null);
    }
}
